<?php


namespace Shuai\Phpwx\Http\Api;

use Illuminate\Support\Facades\Cache;
use Shuai\Phpwx\Phpwx;
/**
 * Api constructor.
 * @param $appid [String] 意同微信文档
 * @param $secret [String] 意同微信文档
 */
class Api extends Phpwx
{

    private function getAccessToken(){

            $value = Cache::remember('wx_access_token', 7200, function(){
            $getAccessUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->secret}";
            $res= json_decode($this->curlGet($getAccessUrl,'get'));
            return $res->access_token;
        });
        return $value;
    }

    /**
     * 发送数据库操作的方法
     * @param $actionType [String] 要进行查询的动作 如： databasequery|databaseupdate|databasedelete|databaseadd|databaseAggregate
     * @param $option [Object] 进行查询的代码，同微信云数据库的js代码
     * @return mixed [Object]
     */
    public function send($actionType,$jscode){

        $url = $this->dbUrl . $actionType . "?access_token=" . $this->getAccessToken();
        $option = [] ;
        $option['env'] = $this->env;
        $option['query'] = $jscode;
        $res= json_decode($this->curlGet($url,'post',json_encode($option)));

        return $res;

    }

    /**
     * 向数据库内插入数据
     * @param $collection [String] 要连接的集合表名
     * @param $data [Array] 要进行操作的数据 格式为 [obj,obj,obj]
     */
    public function addItem($collection,$data){
        $data = json_encode($data);
        $jscode = "db.collection(\"{$collection}\").add({data:{$data}})";
        $action = 'databaseadd';
        return $this->send($action,$jscode);
    }

    /**
     * 更新数据库
     * @param $collection [String] 要连接的集合表名
     * @param $data [object] 要进行操作的数据 格式为 {key:value,key:value....}
     * @return mixed
     */
    public function updateItem($collection,$data){
        $_id = $data['_id'];
        $data = json_encode($data);
        $jscode = "db.collection(\"{$collection}\").where({'_id':'{$_id}'}).update({data:{$data}})";
        $action = 'databaseupdate';
        return $this->send($action,$jscode);
    }

    public  function deleteItem($collection,$id){

        $codejs = "db.collection(\"{$collection}\").where({_id:\"{$id}\"}).remove()";
        return $this->send('databasedelete',$codejs);
    }


}
